import YAML = require('yaml')
import path from "path";
import fs = require('fs')
/*
dbaddr: 127.0.0.1:5432
username: postgres
password: Xh123pswd
dbname: iotbase
type: postgres
redisoption:
  addr: 127.0.0.1:6379
  username: ""
  password: ""
  index: 0
addr: tcp://192.168.10.28:1883
un: iotbase
pwd: Mima2021@)@!
htinterval: 20
topicprefix: /scenery-zw/
*/
declare interface MqttConnOpt {
  addr: string;
  un: string;
  pwd: string;
  htinterval: number;
  topicprefix: string;
}

declare interface RedisConnOpt {
  addr: string;
  username: number;
  password: string;
  index: number;
}
declare interface DBConnOpt {
  dbaddr: string;
  host: string;
  port: number;
  username: string;
  password: string;
  dbname: string;
  redisoption: RedisConnOpt;
  //database: string;
}

declare interface SelfOpt {
  id: string;
  secret: string;

}


class Config {
  mqttOption!: MqttConnOpt;
  dbOption!: DBConnOpt;
  selfOption!: SelfOpt;
  path: string = ""
  //redisOption!: RedisConnOpt;


  constructor() {
    try {
      let cfgPath = path.resolve(__dirname, `../../../../../../cfg/`)
      console.log("****************", cfgPath)
      this.path = cfgPath
      let buffer = fs.readFileSync(cfgPath + '/db.yaml', 'utf8');
      this.dbOption = YAML.parse(buffer);
      let parts = this.dbOption.dbaddr.split(":")
      if (parts.length == 2) {
        this.dbOption.host = parts[0]
        this.dbOption.port = parseInt(parts[1])
      }
      buffer = fs.readFileSync(cfgPath + '/mqtt.yaml', 'utf8');
      this.mqttOption = YAML.parse(buffer);

      buffer = fs.readFileSync(cfgPath + '/self.yaml', 'utf8');
      this.selfOption = YAML.parse(buffer);
      if(!this.selfOption.secret){
        this.selfOption.secret = "iotbase"
      }


    } catch (err) {
      console.log(err)
    }
  }
}
let Cfg = new Config()

export {
  MqttConnOpt,
  DBConnOpt,
  //RedisConnOpt,
  Config,
  Cfg,

}